package com.md.youyouhui.ui.home;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.md.youyouhui.R;
import com.md.youyouhui.databinding.ActivityDirectPayBinding;
import com.md.youyouhui.databinding.AdapterDirectPayBinding;
import com.md.youyouhui.net.Constants;
import com.md.youyouhui.net.response.CouponAvailableResponse;
import com.md.youyouhui.net.response.DirectPayResponse;
import com.md.youyouhui.net.response.WxPayResponse;
import com.md.youyouhui.ui.BaseActivity;
import com.md.youyouhui.ui.adapter.DataBoundViewHolder;
import com.md.youyouhui.ui.pay.AuthResult;
import com.md.youyouhui.ui.pay.PayResult;
import com.md.youyouhui.ui.pay.SelectCouponActivity;
import com.md.youyouhui.ui.pay.SelectOilActivity;
import com.md.youyouhui.utils.DialogLoginUtils;
import com.md.youyouhui.utils.SharedPreferencesUtils;
import com.md.youyouhui.utils.ToastUtils;
import com.md.youyouhui.view.MainViewModel;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.List;
import java.util.Map;

/**
 * Created by AdministratorZJ
 * on 2019/4/25.
 */
public class DirectPayActivity extends BaseActivity {
    private ActivityDirectPayBinding payBinding;
    private int meal = 0;
    private MyAdapter adapter;
    private MainViewModel viewModel;
    private String cardId, mealId, couponId, couponPrice;
    /** 商户私钥，pkcs8格式 */
    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
    /**
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "";
    public static final String RSA_PRIVATE = "";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(ct, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(ct, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(ct, "授权成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(ct, "授权失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };
    private double money;
    private IWXAPI msgApi;
    private String addressId;
    private String token;

    @Override
    public void setContentLayout() {
        payBinding = DataBindingUtil.setContentView(this, R.layout.activity_direct_pay);
        viewModel = new MainViewModel();
    }

    @Override
    public void initView() {
        setSupportActionBar(payBinding.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public void initData() {
        token = SharedPreferencesUtils.getString(this, Constants.USER_TOKEN, "");
        msgApi = WXAPIFactory.createWXAPI(this, null);
        // 将该app注册到微信
        msgApi.registerApp(Constants.WXKEY);
        adapter = new MyAdapter();
        payBinding.payRecycler.setAdapter(adapter);
        payBinding.payIv.setOnClickListener(v -> {
            if (TextUtils.isEmpty(token)) {
                new DialogLoginUtils().dialogLogin(this);
                return;
            }
            startActivityForResult(new Intent(ct, SelectOilActivity.class), 100);
        });
        payBinding.payCouponLayout.setOnClickListener(v -> {
            if (TextUtils.isEmpty(token)) {
                new DialogLoginUtils().dialogLogin(this);
                return;
            }
            String all = payBinding.payAllPrice.getText().toString();
            String[] split = all.split("¥");
            startActivityForResult(new Intent(ct, SelectCouponActivity.class).putExtra("price", split[1]), 101);
        });
        payBinding.pay.setOnClickListener(v -> {
            if (TextUtils.isEmpty(token)) {
                new DialogLoginUtils().dialogLogin(this);
                return;
            }
            if (TextUtils.isEmpty(cardId)) {
                Toast.makeText(ct, "请选择要充值的油卡", Toast.LENGTH_SHORT).show();
                return;
            }
            showPayDialog();
            //Toast.makeText(ct, "成功支付" + payBinding.payAllPrice.getText() + "元", Toast.LENGTH_SHORT).show();
        });
        getDirectMeal(0, false);
    }

    private void showPayDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_pay, null);
        builder.setView(view);
        builder.setMessage("请选择支付方式");
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        ConstraintLayout aliPay = view.findViewById(R.id.aliPay);
        ConstraintLayout wxPay = view.findViewById(R.id.wxPay);
        aliPay.setOnClickListener(v -> {
            payMoneyCard();
            alertDialog.dismiss();
        });
        wxPay.setOnClickListener(v -> {
            //Toast.makeText(this, "敬请期待", Toast.LENGTH_SHORT).show();
             wxPayService();
            alertDialog.dismiss();
        });
    }

    private void wxPayService() {
        String all = payBinding.payAllPrice.getText().toString();
        String[] split = all.split("¥");
        viewModel.payMoney(mealId, split[1], cardId, couponId, "1").observe(this, listResource -> {
            assert listResource != null;
            switch (listResource.status) {
                case LOADING:
                    payBinding.progress.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    payBinding.progress.setVisibility(View.GONE);
                    Map<String, String> jsonObject = (Map<String, String>) listResource.data;
                    if (null == jsonObject) {
                        Toast.makeText(ct, "获取支付wx_orderInfo为null", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    String appid = jsonObject.get("appid");
                    String partnerid = jsonObject.get("partnerid");
                    String prepayid = jsonObject.get("prepayid");
                    String packageValue = jsonObject.get("package");
                    String noncestr = jsonObject.get("noncestr");
                    String timestamp = jsonObject.get("timestamp");
                    String sign = jsonObject.get("sign");
                    WxPayResponse wxPayResponse = new WxPayResponse();
                    wxPayResponse.appid = appid;
                    wxPayResponse.partnerid = partnerid;
                    wxPayResponse.prepayid = prepayid;
                    wxPayResponse.packageValue = packageValue;
                    wxPayResponse.noncestr = noncestr;
                    wxPayResponse.timestamp = timestamp;
                    wxPayResponse.sign = sign;
                    wxAli(wxPayResponse);
                    break;
                case ERROR:
                    payBinding.progress.setVisibility(View.GONE);
                    ToastUtils.errMake(this, listResource.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    private void payMoneyCard() {
        String all = payBinding.payAllPrice.getText().toString();
        String[] split = all.split("¥");
        viewModel.payMoney(mealId, split[1], cardId, couponId, "0").observe(this, listResource -> {
            assert listResource != null;
            switch (listResource.status) {
                case LOADING:
                    payBinding.progress.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    payBinding.progress.setVisibility(View.GONE);
                    String data = (String) listResource.data;
                    if (TextUtils.isEmpty(data)) {
                        Toast.makeText(ct, "获取支付orderInfo为null", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    payAli(data);
                    break;
                case ERROR:
                    payBinding.progress.setVisibility(View.GONE);
                    ToastUtils.errMake(this, listResource.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    private void payAli(String orderInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(DirectPayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void wxAli(WxPayResponse data) {
        PayReq request = new PayReq();
        request.appId = data.appid;
        request.partnerId = data.partnerid;
        request.prepayId = data.prepayid;
        request.packageValue = data.packageValue;
        request.nonceStr = data.noncestr;
        request.timeStamp = data.timestamp;
        request.sign = data.sign;
        msgApi.sendReq(request);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            if (null == data) {
                return;
            }
            cardId = data.getStringExtra("id");
            String type = data.getStringExtra("type");
            if ("1".equals(type)) {
                payBinding.payIv.setImageResource(R.drawable.shihua);
            } else {
                payBinding.payIv.setImageResource(R.drawable.shiyou);
            }
            //Toast.makeText(ct, payId, Toast.LENGTH_SHORT).show();
            String num = data.getStringExtra("num");
            payBinding.directSelect.setText(num);
        } else if (requestCode == 101 && resultCode == RESULT_OK) {
            if (null == data) {
                return;
            }
            couponId = data.getStringExtra("id");
            couponPrice = data.getStringExtra("price");
            payBinding.payCouponNum.setText(String.format("%s元", couponPrice));
            /*String all = payBinding.payAllPrice.getText().toString();
            String[] split = all.split("¥");
            //原总价减去优惠券
            Double price = Double.parseDouble(split[1]) - Double.parseDouble(couponPrice);
            payBinding.payAllPrice.setText("¥" + price);
            double savePrices = money + Double.parseDouble(couponPrice);
            payBinding.paySave.setText("(省" + savePrices + ")");*/
            getDirectMeal(Double.parseDouble(couponPrice), true);
        }
    }


    private void getDirectMeal(double couponPrice, boolean isSelect) {
        viewModel.directPay().observe(this, listResource -> {
            assert listResource != null;
            switch (listResource.status) {
                case LOADING:
                    payBinding.progress.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    payBinding.progress.setVisibility(View.GONE);
                    List<DirectPayResponse> data = listResource.data;
                    if (null == data) {
                        return;
                    }
                    mealId = data.get(meal).id;
                    Double payPrice = data.get(meal).needMoney - couponPrice;
                    payBinding.payAllPrice.setText("¥" + payPrice);
                    Double originalMoney = data.get(meal).originalMoney;
                    money = originalMoney - payPrice;
                    payBinding.paySave.setText("省(" + money + ")");
                    adapter.upDate(data);
                   /* String all = payBinding.payAllPrice.getText().toString();
                    String[] split = all.split("¥");
                    if (!isSelect) {
                        //没有选择优惠券，还是显示有多少张优惠券
                        getCouponAvailable("", split[1]);
                    }*/
                    break;
                case ERROR:
                    payBinding.progress.setVisibility(View.GONE);
                    ToastUtils.errMake(this, listResource.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    private void getCouponAvailable(String id, String price) {
        viewModel.couponAvailable(id, price).observe(this, couponAvailableResponse -> {
            assert couponAvailableResponse != null;
            switch (couponAvailableResponse.status) {
                case LOADING:
                    payBinding.progress.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    payBinding.progress.setVisibility(View.GONE);
                    List<CouponAvailableResponse> data = couponAvailableResponse.data;
                    if (null == data) {
                        return;
                    }
                    payBinding.payCouponNum.setText(String.format("%d张", data.size()));
                    break;
                case ERROR:
                    payBinding.progress.setVisibility(View.GONE);
                    ToastUtils.errMake(this, couponAvailableResponse.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    class MyAdapter extends RecyclerView.Adapter<DataBoundViewHolder<AdapterDirectPayBinding>> {
        List<DirectPayResponse> data;
        Double couponMoney;

        public void upDate(List<DirectPayResponse> data) {
            this.data = data;
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public DataBoundViewHolder<AdapterDirectPayBinding> onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            AdapterDirectPayBinding binding = DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()), R.layout.adapter_direct_pay, viewGroup, false);
            return new DataBoundViewHolder<>(binding);
        }

        @Override
        public void onBindViewHolder(@NonNull DataBoundViewHolder<AdapterDirectPayBinding> holder, int i) {
            if (meal == i) {
                holder.binding.directBg.setBackgroundResource(R.drawable.add_yellow_bg);
                holder.binding.directPrice.setEnabled(true);
                holder.binding.direct1.setEnabled(true);
                holder.binding.directNewPrice.setEnabled(true);
                holder.binding.direct2.setEnabled(true);
            } else {
                holder.binding.directBg.setBackgroundResource(R.drawable.add_blank_bg);
                holder.binding.directPrice.setEnabled(false);
                holder.binding.direct1.setEnabled(false);
                holder.binding.directNewPrice.setEnabled(false);
                holder.binding.direct2.setEnabled(false);
            }
            holder.binding.directPrice.setText(data.get(i).originalMoney + "元");
            holder.binding.directNewPrice.setText(String.valueOf(data.get(i).needMoney));
            holder.itemView.setOnClickListener(v -> {
                couponPrice = "";
                payBinding.payCouponNum.setText(couponPrice);
                meal = i;
                mealId = data.get(i).id;
                if (TextUtils.isEmpty(couponPrice)) {
                    couponMoney = 0.0;
                } else {
                    couponMoney = Double.parseDouble(couponPrice);
                }
                Double payPrice = data.get(i).needMoney - couponMoney;
                Double originalMoney = data.get(i).originalMoney;
                notifyDataSetChanged();
                payBinding.payAllPrice.setText("¥" + payPrice);
                money = originalMoney - payPrice;
                payBinding.paySave.setText("省(" + money + ")");

               /* String all = payBinding.payAllPrice.getText().toString();
                String[] split = all.split("¥");
                getCouponAvailable("", split[1]);*/
            });
        }

        @Override
        public int getItemCount() {
            return null == data ? 0 : data.size();
        }
    }
}
